use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::customer_socials::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub customer_id: String,
    pub provider: String,
    pub user_id: String,
    pub union_id: String,
    pub access_token: String,
    pub refresh_token: String,
    pub reference: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Customer ID must not be empty."))]
    pub customer_id: String,
    #[validate(length(min = 1, message = "Provider must not be empty."))]
    pub provider: String,
    #[validate(length(min = 1, message = "User ID must not be empty."))]
    pub user_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            customer_id: self.customer_id.as_ref().to_owned(),
            provider: self.provider.as_ref().to_owned(),
            user_id: self.user_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::customer_socials::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a customer social by the provided id
    ///
    /// # Errors
    ///
    /// When could not find customer social or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let customer_social = customer_socials::Entity::find()
            .filter(
                model::query::condition()
                    .eq(customer_socials::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        customer_social.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds customer socials by the provided customer id
    ///
    /// # Errors
    ///
    /// When could not find customer socials or DB query error
    pub async fn find_by_customer_id(
        db: &DatabaseConnection,
        customer_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let customer_socials = customer_socials::Entity::find()
            .filter(
                model::query::condition()
                    .eq(customer_socials::Column::CustomerId, customer_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(customer_socials)
    }

    /// Asynchronously creates a customer social and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the customer social into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let customer_social = customer_socials::ActiveModel {
            customer_id: ActiveValue::set(params.customer_id.to_string()),
            provider: ActiveValue::set(params.provider.to_string()),
            user_id: ActiveValue::set(params.user_id.to_string()),
            union_id: ActiveValue::set(params.union_id.to_string()),
            access_token: ActiveValue::set(params.access_token.to_string()),
            refresh_token: ActiveValue::set(params.refresh_token.to_string()),
            reference: ActiveValue::set(params.reference.to_string()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(customer_social)
    }
}

impl ActiveModel {
    /// Updates the customer social's access token
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_access_token(
        mut self,
        db: &DatabaseConnection,
        access_token: String,
    ) -> ModelResult<Model> {
        self.access_token = ActiveValue::set(access_token);
        Ok(self.update(db).await?)
    }

    /// Updates the customer social's refresh token
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_refresh_token(
        mut self,
        db: &DatabaseConnection,
        refresh_token: String,
    ) -> ModelResult<Model> {
        self.refresh_token = ActiveValue::set(refresh_token);
        Ok(self.update(db).await?)
    }

    /// Updates the customer social's reference
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_reference(
        mut self,
        db: &DatabaseConnection,
        reference: String,
    ) -> ModelResult<Model> {
        self.reference = ActiveValue::set(reference);
        Ok(self.update(db).await?)
    }
}
